package com.yunyao.common.core;

import com.yunyao.common.web.enums.ResultMsgEnum;
import com.yunyao.common.web.util.YResult;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.validation.ConstraintViolationException;
import java.util.HashMap;
import java.util.Map;


/**
 * 全局异常处理
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    private static final int PARAM_ERROR = ResultMsgEnum.PARAM_ERROR.getCode();

    /**
     * 数据校验异常 统一返回错误信息
     * 处理参数校验异常
     * @param ex
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Object> handleValidationExceptions(MethodArgumentNotValidException ex) {
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getAllErrors().forEach((error) -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });
        StringBuffer msg = new StringBuffer();
        for (Map.Entry<String, String> entry : errors.entrySet()) {
            msg.append(entry.getValue()+";");
        }
        return new ResponseEntity<Object>(YResult.error(PARAM_ERROR, msg.toString()), HttpStatus.OK);
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public ResponseEntity<Object> handleCustomValidationException(ConstraintViolationException ex) {
        // 可以自定义返回的错误信息格式
        return new ResponseEntity<Object>(YResult.error(PARAM_ERROR, ex.getMessage()), HttpStatus.OK);
    }
}